package nl.saxion.saktiehuis;

import java.util.List;

import nl.saxion.saktiehuis.model.Klant;
import nl.saxion.saktiehuis.model.Order;
import nl.saxion.saktiehuis.model.Product;
import nl.saxion.saktiehuis.service.KlantService;
import nl.saxion.saktiehuis.service.OrderService;
import nl.saxion.saktiehuis.service.ProductService;
import nl.saxion.saktiehuis.webservice.BestelService;
import nl.saxion.saktiehuis.webservice.Bestelling;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("Saktiehuis")
@Transactional
public class SaktiehuisImpl implements Saktiehuis {

	@Autowired
	private OrderService orderService;

	@Autowired
	private KlantService klantService;

	@Autowired
	private ProductService productService;

	@Autowired
	private BestelService bestelService;

	@Override
	public int nieuwOrder(String klantNaam) {
		Klant klant = klantService.getKlant(klantNaam);
		if (klant != null) {
			Order order = new Order();
			order.setKlant(klant);
			order.setDefinitief(false);
			orderService.saveOrUpdate(order);
			return order.getId();
		}
		return -1;
	}

	@Override
	public boolean bestel(int orderNummer, int productNummer, int aantal) {
		Order order = orderService.getOrderById(orderNummer);
		Product product = productService.getProductById(productNummer);
		if (product != null && order != null) {
			orderService.bestel(product, order, aantal);
			return true;
		}
		return false;
	}

	@Override
	public List<Product> getSelectie(String type) {
		return productService.getSelectie(type);
	}

	@Override
	public Order getOverzicht(int orderNummer) {
		return orderService.getOrderById(orderNummer);
	}

	public List<Klant> getKlanten() {
		return klantService.getAlleKlanten();
	}

	@Override
	public boolean bevestigOrder(int orderNummer) {
		Order order = orderService.bevestig(orderNummer);
		if (order != null) {
			bestelService.bestel(prepareBestelling(order));
			return true;
		}
		return false;
	}

	private Bestelling prepareBestelling(Order order) {
		Bestelling bestelling = new Bestelling();
		bestelling.setKlantNaam(order.getKlant().getNaam());
		bestelling.setBestelNr(new Long(order.getId()));
		for (Product product : order.getProducten()) {
			bestelling.getProducten().add(prepareProduct(product));
		}
		return bestelling;
	}

	private nl.saxion.saktiehuis.webservice.Product prepareProduct(
			Product product) {
		nl.saxion.saktiehuis.webservice.Product webserviceProduct = new nl.saxion.saktiehuis.webservice.Product();
		webserviceProduct.setProductNaam(product.getNaam());
		return webserviceProduct;
	}
}
